/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Platform,
    InteractionManager
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import petService from '../lib/services/petService';
import Swiper from 'react-native-swiper';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

export default class AnimalDetails extends Component{
    constructor(props) {
        super(props);
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.page = 1;
        this.timeList = [];
        this.state = {
            animalId:this.props.navigation.state.params.animalId,
            token:this.props.navigation.state.params.token,
            animalObject:{},
            moreIcon:'down',
            labelList:[],
            historyList:ds.cloneWithRows([]),
            canLoadMore:true
            
        }; 
        this.obj={};
    }

    componentDidMount() {
        var $this = this;
        InteractionManager.runAfterInteractions(() => {
            $this.getAnimalDetails();
            $this.getTimeAxis();
        });
    }
    // 渲染标签列表
    renderLabel(){
        var list = this.state.animalObject.pet_tags?this.state.animalObject.pet_tags:[];
        var len = list?list.length:0;
        if(len>0){
            return(
                list.map((item,i)=>{
                    return(
                        <View key={i} style={{borderRadius:3,backgroundColor:'rgb(150,200,237)',marginLeft:10,padding:3,marginTop:10}}>
                            <Text>{item.pet_tag}</Text>
                        </View>
                    )
                })
            )
        }else{
            return(
                <View style={{borderRadius:3,backgroundColor:'rgb(150,200,237)',marginLeft:10,padding:3,marginTop:10}}>
                    <Text>未填写</Text>
                </View>
            )
        }
        
    }
    // 宠物资料
    renderAnimalData(){
        var obj = this.state.animalObject;
        var sexArr = ['GG(公)','MM(母)'];
        var variety = ['猫','狗'];
        var date = new Date().getTime();
        var age = '';
        if(obj.birth_time){
            age = Math.ceil((date/1000 - obj.birth_time)/(60*60*24)) +'天';
        }
        return(
            <View>
                <AnimalData title={'科目'} text={variety[obj.pet_varieties]||'未知生物'}/>
                <AnimalData title={'品种'} text={obj.pet_category||'未填写'}/>
                <AnimalData title={'性别'} text={sexArr[obj.pet_sex]}/>
                <AnimalData title={'年龄'} text={age || '未填写'}/>
                <AnimalData title={'肩高'} text={obj.pet_length||'未填写'}/>
                <AnimalData title={'体重'} text={obj.pet_weight||'未填写'}/>
                <AnimalData title={'性格'} text={obj.pet_character||'未填写'}/>
            </View>
        )
    }
    // 渲染宠物头像
    renderPetImg(){
        var list = this.state.animalObject?this.state.animalObject.pet_imgs:[];
        var len = list?list.length:0;
        if(len==0){
            return(
                <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
                    <ImageWrapper width={width} height={width} icon={'banner1'}/>
                </View>
            )
        }else{
            return(
                list.map((item,i)=>{
                    return(
                        <View key={i} style={{flex:1,justifyContent:'center',alignItems:'center'}}>
                            <ImageWrapper width={width} height={width} icon={{uri:'http://test.520m.com.cn/upload/common/'+item}}/>
                        </View>
                    )
                })
            )
        }
    }
    // 
    pressData(name,url){
        return(
            <View style={{flexDirection:'row',paddingBottom:20}}>
                <ImageWrapper icon={{uri:'http://test.520m.com.cn/upload/thumb/'+url}} style={{borderRadius:10}}/>
                <Text>{name}给您的宠物点了赞</Text>
            </View>
        )
    }
    renderImgList(list){
        if(list.length>0){
            return(
                list.map((item,i)=>{
                    return(
                        <View style={{marginLeft:5,width:50,height:50,marginTop:5}} key={i}>
                            <ImageWrapper icon={{uri:item}} width={50} height={50} style={{borderRadius:5}}/>
                        </View>
                    )
                })
            )
        }   
    }
    imgData(list){
        var arr = list.split(',');
        return(
            <View style={{paddingBottom:20,width:200}}>
                <Text>宠物的新靓照</Text>
                <View style={{flexDirection:'row',flexWrap:'wrap',alignItems: 'stretch'}}>
                    {this.renderImgList(arr)}
                </View>
            </View>
        )
    }
    renderNewAnimal(){
        return(
            <View style={{paddingBottom:20}}>
                <Text>添加了新的宠物</Text>
            </View>
        )
    }
    renderData(text,data){
        return(
            <View style={{paddingBottom:20}}>
                <Text>修改了宠物的{text}为{data}</Text>
            </View>
        )
    }

    renderHistoryItem(rowData){
        if(rowData.status==1){
            return(
                <View>
                    <TimeAxis timeText={rowData.time} icon={'touxiang'} dataItems={this.pressData(rowData.username,rowData.user_head_img)}/>
                </View>
            )
        }else if(rowData.status==2){
            return(
                <View>
                    <TimeAxis timeText={rowData.time} icon={'touxiang'} dataItems={this.imgData(rowData.pet_album_img)}/>
                </View>
            )
        }else if(rowData.status==3){
            return(
                <View>
                    <TimeAxis timeText={rowData.time} icon={'touxiang'} dataItems={this.renderNewAnimal()}/>
                </View>
            )
        }else if(rowData.status==4){
            // var age = '';
            // if(rowData.pet_birth_time){
            //     var date = new Date();
            //     var year = date.getFullYear();
            //     var month = date.getMonth();
            //     var day = date.getDate();
            //     var birthTime = new Date(rowData.pet_birth_time*1000);
            //     var birthYear = birthTime.getFullYear();
            //     var birthMonth = birthTime.getMonth();
            //     var birthDay = birthTime.getDate();
            //     if(year==birthYear){
            //         if(month==birthMonth){
            //             age = day - birthDay + '天';
            //         }else{
            //             age = month - birthMonth + '月';
            //         }
            //     }else{
            //         age = year - birthYear + '年';
            //     }
            // }
            var sexArr = ['GG(公)','MM(母)'];
            var varieties = '其他';
            if(rowData.pet_varieties==0){
                varieties = '猫';
            }else if(rowData.pet_varieties==1){
                varieties = '狗';
            }
            return(
                <View>
                    {rowData.pet_varieties?<TimeAxis timeText={rowData.time} icon={'touxiang'} dataItems={this.renderData('类型',varieties)}/>:<View></View>}
                    {rowData.pet_sex?<TimeAxis timeText={rowData.time} icon={'touxiang'} dataItems={this.renderData('性别',sexArr[rowData.pet_sex])}/>:<View></View>}
                    {rowData.pet_category?<TimeAxis timeText={rowData.time} icon={'touxiang'} dataItems={this.renderData('品种',rowData.cate_name)}/>:<View></View>}
                    {rowData.pet_birth_time?<TimeAxis timeText={rowData.time} icon={'touxiang'} dataItems={this.renderData('年龄',rowData.pet_birth_time2)}/>:<View></View>}
                    {rowData.pet_length?<TimeAxis timeText={rowData.time} icon={'touxiang'} dataItems={this.renderData('身长',rowData.pet_length+'cm')}/>:<View></View>}
                    {rowData.pet_weight?<TimeAxis timeText={rowData.time} icon={'touxiang'} dataItems={this.renderData('重量',rowData.pet_weight+'kg')}/>:<View></View>}
                    {rowData.pet_character?<TimeAxis timeText={rowData.time} icon={'touxiang'} dataItems={this.renderData('性格',rowData.pet_character)}/>:<View></View>}
                    {rowData.pet_signature?<TimeAxis timeText={rowData.time} icon={'touxiang'} dataItems={this.renderData('签名',rowData.pet_signature)}/>:<View></View>}
                    {rowData.onwer_msg?<TimeAxis timeText={rowData.time} icon={'touxiang'} dataItems={this.renderData('宠物留言',rowData.onwer_msg)}/>:<View></View>}
                </View>
            )
        }
        
    }
    render(){
        var data = this.state.animalObject;
        // alert(JSON.stringify(data))
        return (
            <View style={styles.container}>
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={'宠物详情'} 
                    leftPress={()=>this.goBack()}
                    rightText={'主人'}
                    rightTextPress={()=>this.goInformationDetails(data.user_id)}
                    rightTextStyle={{color:'#fff',fontSize:16}}/>
                <ScrollView>
                    <Swiper autoplay={true}  autoplayTimeout={5} showsButtons={false} width={width} height={width}>
                        {this.renderPetImg()}  
                    </Swiper>
                    <View style={{position:'absolute',top:width-30,width:width,height:30,alignItems:'center',left:0,flexDirection:'row'}}>
                        <View style={{alignItems:'center',flexDirection:'row'}}>
                            <Text style={{color:'#fff',fontSize:18,marginLeft:10}}>{data.pet_name}</Text>
                            <ImageWrapper icon={'v'} width={16} height={16} style={{marginLeft:5}}/>
                            <Text style={{fontFamily:'symbol',color:'#f4ea2a',fontSize:18}}>{data.pet_grade}</Text>
                        </View>
                    </View>
                    <View style={{borderBottomWidth:1,borderBottomColor:'#ccc'}}>
                        <TouchableOpacity onPress={()=>this.moreMaterial()}>
                            <TitleItem title={'宠物资料'} more={true} icon={this.state.moreIcon}/>
                        </TouchableOpacity>
                        <View>
                            {this.state.moreIcon=='up'?this.renderAnimalData():null}
                        </View>
                    </View>
                    <View>
                        <TitleItem title={'标签'}/>
                        <View style={{flexDirection:'row',paddingBottom:10,backgroundColor:'#fff'}}>
                            {this.renderLabel()}
                        </View>
                    </View>
                    <View>
                        <TitleItem title={'陪它·时光'}/>
                        <View style={{paddingTop:10,backgroundColor:'#fff'}}>
                            <ListView 
                                style={{marginBottom:20}}
                                dataSource={this.state.historyList}
                                renderRow={(rowData)=>this.renderHistoryItem(rowData)}
                                onEndReached={()=>this.getTimeAxis()}
                                onEndReachedThreshold={1}
                                enableEmptySections={true}/>
                        </View>
                    </View>
                </ScrollView>
            </View>
        )

    }

    goBack(){
        this.props.navigation.goBack();
    }
    // 是否显示宠物详情
    moreMaterial(){
        if(this.state.moreIcon=='down'){
            this.setState({
                moreIcon:'up'
            })
        }else{
            this.setState({
                moreIcon:'down'
            })
        }
    }
    // 跳转到主人详情
    goInformationDetails(personId){
        var $this = this;
        const {navigate} = this.props.navigation;
        navigate('InformationDetails',{personId:personId,token:$this.state.token})
    }
    // 获取数据
    getAnimalDetails(){
        var $this = this;
        petService.detail(function(data){
            // alert(JSON.stringify(data))
            if(data.code==10000){
                var obj = data.data;
                // alert(JSON.stringify(obj))
                $this.setState({
                    animalObject:obj,
                })
                $this.obj = obj;
            }else{
                // alert('哎呀！出错了！')
            }
            
        },$this.state.animalId,$this.state.token)
    }
    // 陪它时光列表
    getTimeAxis(){
        var $this = this;
        if(this.state.canLoadMore){
            petService.axisList(function(data){
                if(data.code==10000){
                    if(data.data.query.countpage>$this.page){
                        $this.timeList = $this.timeList.concat(data.data.pagedata)
                        $this.setState({
                            historyList:$this.state.historyList.cloneWithRows($this.timeList),
                            canLoadMore:true
                        })
                        $this.page++;
                    }else if(data.data.query.countpage==$this.page){
                        $this.timeList = $this.timeList.concat(data.data.pagedata)
                        $this.setState({
                            historyList:$this.state.historyList.cloneWithRows($this.timeList),
                            canLoadMore:false
                        })
                    }
                    
                }
            },$this.state.animalId,$this.state.token,$this.page)
        }
    }
}

class TitleItem extends Component{
    render(){
        return(
            <View style={{flexDirection:'row',alignItems:'center',height:40,backgroundColor:'rgb(79,145,237)',justifyContent:'space-between',paddingLeft:10}}>
                <View>
                    <Text style={{color:'#fff'}}>{this.props.title}</Text>
                </View>
                {this.props.more?<View>
                    <ImageWrapper icon={this.props.icon} style={{tintColor:'#fff',marginRight:10}}/>
                </View>:<View></View>}
            </View>
        )
    }
}

class AnimalData extends Component{
    render(){
        return(
            <View style={{flexDirection:'row',alignItems:'center',height:40,backgroundColor:'#fff',paddingLeft:10,borderBottomWidth:1,borderBottomColor:'#aaa'}}>
                <View style={{width:120}}>
                    <Text>{this.props.title}</Text>
                </View>
                <View>
                    <Text>{this.props.text}</Text>
                </View>
            </View>
        )
    }
}

class TimeAxis extends Component{
    render(){
        return(
            <View style={{flexDirection:'row',backgroundColor:'#fff',paddingLeft:10}}>
                <ImageWrapper style={{position:'absolute',top:0,left:97,borderRadius:13,width:26,height:26,borderRadius:13,zIndex:1000}} icon={this.props.icon}/>
                <View style={{width:85}}>
                    <Text>{this.props.timeText}</Text>
                </View>
                <View style={{borderLeftWidth:1,borderLeftColor:'#B1CFFF',paddingLeft:20,marginLeft:15}}>
                    <View>{this.props.dataItems}</View>
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },
        }),
    },
});